import AccreditDia from '@/components/accreditDia/AccreditDia'
import NoPermissionTem from '@/components/antd-comp/NoPermission'
import ListEmpty from '@/components/antd-comp/empty'
import { showMessage } from '@/components/antd-comp/message'
import TableGrid from '@/components/antd-comp/table'
import { columnsProps } from '@/components/antd-comp/table/constants'
import ThemeBtn from '@/components/antd-comp/theme-btn'
import FouterPage from '@/components/fouter-page'
import InputAntDef from '@/components/input/InputAntDef'
import { Func } from '@/permissions/constants'
import { useDictStore } from '@/store/dictStore'
import { useFuncsStore } from '@/store/funcStore'
import { useRouteStoreHook } from '@/store/routeStore'
import { useBuriedEvent } from '@/util/buried'
import { ExclamationCircleFilled } from '@ant-design/icons'
import { Modal, Tooltip } from 'antd'
import { useContext, useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { useNavigate } from 'react-router-dom'
import TabsDropComponent from '../../components/TabsDropComponent/index'
import { userContext } from '../../contexts/userContext'
import { deleteFileLib, deleteFileLibCount, readFileLibDatabase } from '../../controllers/API'
import { useTable } from '../../util/hook'
import { knowledgeUsedCountByFlowApi } from '../workflow/API'
import { MODELS_OBJ } from './constants'
import './css/index.css'

const { confirm } = Modal

// table的唯一id
const getUniqueKey = (record: any) => record.id

export default function FileLibPage() {
  const { t } = useTranslation()
  /**
   * 涉及顶部路由信息，在对应页面进行处理
   */
  const routeNames = [t('menu.knowledge')]
  useRouteStoreHook(routeNames)

  /**
   * 功能权限限制
   */
  const { hasFuncPermission } = useFuncsStore()

  const { user } = useContext(userContext)

  const navigate = useNavigate()
  const [num, setNum] = useState(0)
  const [name, setName] = useState(undefined)

  const linkToCreate = (path, type) => {
    navigate(path, { state: { type } })
  }

  // 类型选择
  const [typeList, setTypeList] = useState([])
  const typeMap = useRef({})
  const { loadDictOptions } = useDictStore()
  const loadTypeList = (type = 'category') => {
    loadDictOptions(type).then(res => {
      if (res) {
        res.unshift({
          id: 0,
          label: '全部类型',
          value: 'all'
        })
        setTypeList(res)
        const typeInfo = {}
        res.forEach(type => {
          typeInfo[type.id] = type.label
        })
        typeMap.current = typeInfo
      } else {
        setTypeList([
          {
            id: 0,
            label: t('all')
          }
        ])
      }
    })
  }
  const { fileLibBuriedEvent } = useBuriedEvent()  
  useEffect(() => {
    //loadTypeList()
    setTypeList([
      {
        id: 0,
        label: t('all'),
        value: 'all'
      },
      {
        id: -1,
        label: '企业知识库',
        value: 'enterprise'
      },
      {
        id: 1,
        label: '个人知识库',
        value: 'personal'
      },
    ])

    const typeInfo = {}
    typeInfo[-1] = '企业知识库'
    typeInfo[1] = '个人知识库'
    typeMap.current = typeInfo
  }, [])

  const {
    page,
    pageSize,
    data: datalist,
    total,
    loading,
    setPage,
    // search,
    reload,
    filterData,
    setLoading
  } = useTable(
    {},
    param => readFileLibDatabase(param.page, param.pageSize, param.name, param.type),
    true,
    () => hasFuncPermission([Func.knowledge.query])
  )

  const handleDelete = async e => {
    fileLibBuriedEvent({
      page: '知识库页面',
      event_name: '【删除】按钮',
      data_id: e.id
    })
    // 删除权限限制
    if (!hasFuncPermission([Func.knowledge.del])) {
      return
    }

    try {
      const [ast_used_res, flow_used_res]: any[] = await Promise.all([
        deleteFileLibCount(e.id),
        knowledgeUsedCountByFlowApi(e.id)
      ])

      const ast_used_count = ast_used_res?.count || 0
      const flow_used_count = flow_used_res?.count || 0
      confirm({
        title: t('prompt'),
        icon: <ExclamationCircleFilled style={{ color: 'red' }} />,
        // content: t('lib.confirmDeleteLibrary'),
        content: `${
          ast_used_count || flow_used_count
            ? `知识库当前被${ast_used_count}个智能体、${flow_used_count}个工作流引用。删除后，将导致所有引用的智能体或工作流无法使用，操作无法撤回，确认删除该知识库?`
            : t('lib.confirmDeleteLibrary')
        } `,
        okText: t('delete'),
        okType: 'danger',
        cancelText: t('cancel'),
        autoFocusButton: null,
        centered: true,
        destroyOnClose: true,
        onCancel() {
          fileLibBuriedEvent({
            page: '知识库页面',
            event_name: '取消【删除】知识库按钮',
            data_id: e.id
          })
        },
        onOk() {
          setLoading(true)
          deleteFileLib(e.id)
            .then(() => {
              fileLibBuriedEvent({
                page: '知识库页面',
                event_name: '确定【删除】知识库按钮',
                data_id: e.id,
                detail: JSON.stringify({ 结果: '成功' })
              })
              reload()
              showMessage({
                content: '删除成功',
                type: 'success'
              })
            })
            .catch(() => {
              fileLibBuriedEvent({
                page: '知识库页面',
                event_name: '确定【删除】知识库按钮',
                data_id: e.id,
                detail: JSON.stringify({ 结果: '失败' })
              })
              setLoading(false)
            })
            .finally(() => {
              setLoading(false)
            })
        }
      })
    } catch (error) {
      console.error('Failed to get delete count', error)
    }
  }
  const handleEdit = data => {
    console.log('handleEdit', data)
    fileLibBuriedEvent({
      page: '知识库页面',
      event_name: '【编辑】按钮',
      data_id: data.id
    })
    if (!hasFuncPermission([Func.knowledge.edit])) {
      return
    }
    navigate('/filelib/create/' + data.id, { state: { type: 'edit', data } })
  }
  
  const seleCarFun = (data, id) => {
    setNum(id)
    
    filterData({ name, type: id })
    fileLibBuriedEvent({
      page: '知识库页面',
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: name, 类型: id })
    })
  }

  const beforeSearch = val => {
    fileLibBuriedEvent({
      page: '知识库页面',
      event_name: '搜索条件',
      detail: JSON.stringify({ 搜索条件: val, 类型: num })
    })
    setName(val)
    filterData({ name: val, type: num })
  }

  const handleTypeInfo = val => {
    return typeMap.current[val] || '--'
  }
  /* 权限 */
  const [accredit, setAccredit] = useState(false)

  // 定义tableColumns
  const tableColumns: columnsProps[] = [
    {
      dataIndex: 'name',
      title: t('lib.knowledge'),
      width: 260,
      fixed: 'left',
      render: (text, record, _index) => (
        <div className="flexRowStart">
          {record.icon && record.icon !== 'None' && (
            <img
              src={record.icon}
              alt="icon"
              style={{
                height: '36px',
                width: '36px',
                margin: '0 8px 0 0',
                borderRadius: '4px',
                display: 'inline'
              }}
            />
          )}
          <div className="flexCol fileLibPage_oneCase">
            <Tooltip title={text}>
              <span className="fileLibPage_name domOverflowEllip">{text}</span>
            </Tooltip>
            <Tooltip title={record.description}>
              <span className="fileLibPage_description domOverflowEllip">{record.description}</span>
            </Tooltip>
          </div>
        </div>
      ),
      ellipsis: {
        showTitle: false
      },
      className: 'filelib_name_column'
    },
    {
      dataIndex: 'catetory',
      title: t('lib.type'),
      width: 100,
      render: (text, _record, _index) => handleTypeInfo(text)
    },
    {
      dataIndex: 'file_count',
      title: t('lib.fileNum'),
      width: 100,
      render: (text, _record, _index) => {
        return _record?.file_count > 10000 ? '10K+' : _record.file_count || '--'
      }
    },
    {
      dataIndex: 'model',
      title: t('lib.model'),
      width: 198,
      render: (text, _record, _index) => MODELS_OBJ[text] || text || '--'
    },
    {
      dataIndex: 'user_name',
      title: t('lib.createUser'),
      width: 140,
      render: (text, _record, _index) => {
        return (
          <div className="flexRowStart">
            <Tooltip title={text}>
              <span className="fileLibPage_user_name domOverflowEllip">{text}</span>
            </Tooltip>
          </div>
        )
      }
    },
    {
      dataIndex: 'create_time',
      title: t('createTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },
    {
      dataIndex: 'update_time',
      title: t('updateTime'),
      width: 180,
      render: (text, _record, _index) => text?.replace('T', ' ')
    },

    {
      dataIndex: 'operation',
      title: t('operations'),
      fixed: 'right',
      width: 200,
      render: (_text, record, _index) => (
        <div className="ml-[-16px] bg-inherit">
          {/* <span onClick={() => setAccredit(true)} className="tableSettingName ml-[16px] px-0 text-[#006BFD]">
            授权
          </span> */}
          <span
            onClick={e => {
              fileLibBuriedEvent({
                page: '知识库页面',
                event_name: '【详情】按钮',
                data_id: record.id
              })
              if (hasFuncPermission([Func.knowledge.fileList])) {
                navigate(`/filelib/${record.id}`)
              }
            }}
            className="migu-font-400 ml-[16px] cursor-pointer text-[#006BFD] no-underline hover:underline"
          >
            {t('lib.details')}
          </span>
          {(user.user_id === record.user_id || (user.role.includes("enterprise_admin") && record.catetory == -1)) 
            && <span onClick={() => handleEdit(record)} className="tableSettingName ml-[16px] px-0 text-[#006BFD]">
              {t('edit')}
            </span>
          }

          {(user.user_id === record.user_id || (user.role.includes("enterprise_admin") && record.catetory == -1))  
            && <span onClick={() => handleDelete(record)} className="tableSettingName ml-[16px] px-0 text-[#FA514B]">
            {t('delete')}
          </span>}
          {/* 为了实现右侧fix时border-radius额外增加的遮罩层 */}
          <div className="common-table-right-fixed-layer2">{''}</div>
          <div className="common-table-right-fixed-layer3">{''}</div>
        </div>
      )
    }
  ]

  // table的分页、排序、筛选变化时触发
  const handleTableChange = (values: any) => {
    console.log('values', values)
  }

  if (!hasFuncPermission([Func.knowledge.menu], false)) {
    return <NoPermissionTem />
  }
  return (
    <div className="relative h-full min-w-[600px] bg-[#f5f7fb]">
      {loading && (
        <div className="absolute left-0 top-0 z-10 flex h-full w-full items-center justify-center bg-[rgba(255,255,255,0.6)] dark:bg-blur-shared">
          <span className="loading loading-infinity loading-lg"></span>
        </div>
      )}
      <div className="filelib-container rounded-[6px]">
        <div className="flexRowJustBet flex py-[22px] pl-[24px] pr-[32px]">
          <div className="flexRowStart">
            <TabsDropComponent
              backColor={'#F5F7FB'}
              list={typeList}
              num={num}
              tabsDropFun={seleCarFun}
              style={{ marginRight: '16px' }}
            ></TabsDropComponent>
            <InputAntDef
              searchFun={e => {
                beforeSearch(e.target.value)
              }}
              placeholder={t('lib.enterName')}
            ></InputAntDef>
          </div>
          <div className=" flex items-center justify-end gap-4">
            <ThemeBtn
              className="migu-font-600 h-[36px] w-[92px]"
              onClick={() => {
                fileLibBuriedEvent({
                  page: '知识库页面',
                  event_name: '【创建】知识库按钮'
                })
                if (!hasFuncPermission([Func.knowledge.add])) {
                  return
                }
                linkToCreate('/filelib/create', 'create')
              }}
            >
              {t('create')}
            </ThemeBtn>
          </div>
        </div>
        <div className="relative top-[0] h-[calc(100vh-196px)] max-h-[calc(100vh-196px)] overflow-y-scroll px-[24px] scrollbar-hide">
          <TableGrid
            tableInfo={{
              tableData: datalist,
              tableColumns,
              getUniqueKey, // 唯一id
              // tableIsLoading: loading,
              getTableChangeValues: handleTableChange, // 获取table事件
              scrollHeight: 'calc(100vh - 280px)',
              scrollWidth: 1160
            }}
            emptyComponent={
              !loading && !datalist?.length ? (
                <ListEmpty style={{ height: 'calc(100vh - 314px)', margin: 0 }} />
              ) : (
                <div style={{ height: 'calc(100vh - 314px)', background: '#ffffff', margin: 0 }}></div>
              )
            }
          />
        </div>
        {/* fouter */}
        {!loading && datalist?.length > 0 && (
          <FouterPage
            className="filelib-bottom-box filelib-gray-text rounded-[6px]"
            style={{ background: '#FFFFFF' }}
            page={page}
            pageSize={pageSize}
            total={total}
            setPage={newPage => setPage(newPage)}
          ></FouterPage>
        )}
      </div>
      {/* 分配权限 */}
      {accredit && (
        <AccreditDia
          cancel={() => {
            setAccredit(false)
          }}
          submit={() => {
            setAccredit(false)
          }}
        />
      )}
    </div>
  )
}
